package client.comm.baoding.fragment

import android.content.Intent
import android.os.Parcelable
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.core.view.ViewCompat
import androidx.core.widget.NestedScrollView
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import client.comm.baoding.R
import client.comm.baoding.adapter.HomeTjGoodAdapter
import client.comm.baoding.adapter.JxGood2Adapter
import client.comm.baoding.adapter.SyPagingHeaderAdapter
import client.comm.baoding.api.bean.GoodsIndex
import client.comm.baoding.databinding.FragmentTabnewBinding
import client.comm.baoding.ui.SearchActivity
import client.comm.baoding.ui.TabOne2Activity
import client.comm.baoding.ui.TuiGuangActivity
import client.comm.baoding.ui.vm.MainViewModel
import client.comm.baoding.widget.HorizontalPageLayoutManager
import client.comm.baoding.widget.PagingScrollHelper
import client.comm.commlib.base.BaseFragment
import client.comm.commlib.base.PagerFooterAdapter
import client.comm.commlib.base.SyBannerAdapter
import client.comm.commlib.comm_ui.draw.SpaceItemBottomWhiteDecoration
import client.comm.commlib.getScreenWidth
import client.comm.commlib.network.data.PagingJsonResult
import client.comm.commlib.utils.Util
import client.comm.commlib.widget.EmptyLayout
import com.bumptech.glide.request.RequestOptions
import com.google.gson.Gson
import com.youth.banner.indicator.CircleIndicator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class TabHomeNewFragment : BaseFragment<FragmentTabnewBinding, MainViewModel>() {

    override fun getViewId(): Int {
        return R.layout.fragment_tabnew
    }

    var goodsIndex: GoodsIndex? = null
    var isInit: Boolean = false

    val adapter: HomeTjGoodAdapter by lazy {
        HomeTjGoodAdapter(requireContext(), mImgLoader).apply {
            refreshLoading = {
                if (itemCount == 0) {
                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_LOADING
                }
            }
            refreshNotLoading = {
                binding.refreshLayout.isRefreshing = false
                if (itemCount == 0) {
                    binding.emptyLayout.errorType = EmptyLayout.NODATA
                } else {
                    binding.emptyLayout.visibility = View.GONE
                }

            }
            refreshError = {
                if (itemCount == 0)
                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
            }
        }
    }

    val headerAdapter: SyPagingHeaderAdapter by lazy {
        SyPagingHeaderAdapter(mImgLoader, requireContext())
    }

    override fun initViewModel(): MainViewModel = createViewModel()

    override fun initWidget() {
//        binding.statusBar.post {
//            val h = Util.getStatusBarHeight(requireContext())
//            val p = binding.statusBar.layoutParams
//            p.height = h
//            binding.statusBar.layoutParams = p
//            Util.setBg(resources!!.getColor(R.color.main_color), requireActivity().window)
//            val controller = ViewCompat.getWindowInsetsController(binding.root)
//            controller?.isAppearanceLightStatusBars = true
//        }
        binding.apply {
            event = this@TabHomeNewFragment
        }
        initRv()
        getGoodsIndex()

    }

    fun goSearch() {
        startActivity(Intent(requireContext(), SearchActivity::class.java))
    }

    private fun initRv() {
        val layoutManager = LinearLayoutManager(context)
        binding.recyclerView.addItemDecoration(SpaceItemBottomWhiteDecoration(10))
        binding.recyclerView.layoutManager = layoutManager
        binding.recyclerView.adapter = adapter.withLoadStateHeaderAndFooter(
            header = headerAdapter,
            footer = PagerFooterAdapter()
        )
        binding.refreshLayout.setOnRefreshListener {
            adapter.refresh()
            viewModel.userInfo()
        }
        binding.emptyLayout.setOnClickListener {
            adapter.refresh()
        }


        viewModel.callUser.observe(this, Observer {
            it?.let {
                if (it.isSuccess) {
                    headerAdapter.userInfo = it.data
                    headerAdapter.notifyDataSetChanged()
                }
                binding.refreshLayout.isRefreshing = false
            }
        })
    }


    private fun getGoodsIndex() {
        lifecycleScope.launch {
            viewModel.pagingDataAuto(20, hold = {
                var ret = viewModel.server.goods_index_p(it).body()
//                if (binding.recyclerView.adapter == null) {
//                    binding.recyclerView.adapter = adapter.withLoadStateHeaderAndFooter(
//                        header = headerAdapter,
//                        footer = PagerFooterAdapter()
//                    )
//                }

                ret?.let {
                    val g = Gson()
                    if (!g.toJson(headerAdapter.goodsIndex).equals(g.toJson(it.data))) {
                        withContext(Dispatchers.Main) {
                            headerAdapter.goodsIndex = it.data
                            headerAdapter.notifyDataSetChanged()
                        }
                    }
                }

                PagingJsonResult(
                    list = ret?.data?.tj_goods_list,
                    code = ret?.code,
                    message = ret?.message
                )
            }).collect {
                adapter.submitData(it)
            }
        }
    }

    //购物车
    fun onShopCart(position: Int) {
        changeMainTab?.invoke(position)
    }

    fun tuiguang() {
        requireContext().startActivity(Intent(context, TuiGuangActivity::class.java))
    }

    var changeMainTab: ((position: Int) -> Unit)? = null
    var changeCheckTab: ((position: Int) -> Unit)? = null
    var notice: ((ArrayList<GoodsIndex.Article>) -> Unit)? = null


    fun changeCheckTab(position: Int) {
        changeCheckTab?.invoke(position)
    }

    fun goNotice() {
        notice?.invoke(goodsIndex!!.article_list)
    }

    override fun onResume() {
        super.onResume()
        viewModel.userInfo()
    }


}